package com.example.administrator.androidros.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.provider.Settings;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import org.w3c.dom.Document;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Miscellaneous agent utility methods.
 */
public class AgentUtils {

    /**
     * Package Info
     */
    private static PackageInfo packageInfo = null;

    /**
     * Get Package Info
     */
    public static PackageInfo getPackageInfo(Context context) {
        if (packageInfo == null) {
            try {
                packageInfo = context.getPackageManager().getPackageInfo(
                        context.getPackageName(), 0);
            } catch (NameNotFoundException e) {
                packageInfo = new PackageInfo();
            }
        }
        return packageInfo;
    }

    /**
     * Decode a bitmap
     */
    public static Bitmap decodeBitmap(String path, double needSize) {
        Bitmap bitmap = null;
        // Decode image size
        BitmapFactory.Options bfo = new BitmapFactory.Options();
        bfo.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, bfo);
        // Calculate scale
        int scale = (int) Math.round(Math.sqrt(bfo.outHeight * bfo.outWidth)
                / needSize);
        if (scale < 1) {
            scale = 1;
        }
        // Decode with inSampleSize
        BitmapFactory.Options resize = new BitmapFactory.Options();
        resize.inSampleSize = scale;
        Log.e("inSampleSize", scale + "");
        bitmap = BitmapFactory.decodeFile(path, resize);
        return bitmap;
    }

    /**
     * ネットワ—クの可用性をチェックする。
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isAvailable());
        // return true;
    }

    /**
     * Get file from Bytes[]
     */
    public static File getFileFromBytes(byte[] btyes, String outputFile) {
        File file = null;
        BufferedOutputStream stream = null;
        FileOutputStream fstream = null;
        try {
            file = new File(outputFile);
            fstream = new FileOutputStream(file);

            stream = new BufferedOutputStream(fstream);
            stream.write(btyes);
            stream.close();
            fstream.close();
        } catch (FileNotFoundException e) {
            Log.e("AgentUtils", "getFileFromBytes", e);
        } catch (IOException e) {
            Log.e("AgentUtils", "getFileFromBytes", e);
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    Log.e("AgentUtils", "getFileFromBytes", e);
                }
            }
            if (fstream != null) {
                try {
                    fstream.close();
                } catch (IOException e) {
                    Log.e("AgentUtils", "getFileFromBytes", e);
                }
            }
        }
        return file;
    }

    /**
     * sp转为px
     */
    public static int sp2px(Context context, float spValue) {
        float fontScale = context.getResources().getDisplayMetrics().density;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * dip转为PX
     */
    public static int dip2px(Context context, float dipValue) {
        return DisplayHelper.dpToPx((int) dipValue);
//        float fontScale = context.getResources().getDisplayMetrics().density;
//        return (int) (dipValue * fontScale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 图片转字节数组
     *
     * @param bitmap
     * @return
     */
    public static byte[] getBytesFromBitmap(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();
        return bytes;
    }

    /**
     * Binaryでイメージオブジェクトを取得する。<BR>
     *
     * @param param Binaryオブジェクト
     * @return Bitmap メージオブジェクト
     * @author zhaosx
     */
    public static Bitmap getBitmapFromByte(byte[] param) {
        if (param != null && param.length > 0) {
            return BitmapFactory.decodeByteArray(param, 0, param.length);
        }
        return null;
    }

    /**
     * イメージオブジェクトでBinaryを取得する。<BR>
     *
     * @param bitmap
     * @return
     */
    public static byte[] bitmapToBytes(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        byte[] result = null;
        ByteArrayOutputStream os = null;
        try {
            os = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.PNG, 100, os);
            result = os.toByteArray();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    Log.e("AgentUtils", "bitmapToBytes", e);
                }
            }
        }
        return result;
    }

    /**
     * 焦点を獲得する
     *
     * @param view
     */
    public static void getFocus(View view) {
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        view.requestFocusFromTouch();
    }

    /**
     * 打开图片
     *
     * @param param
     * @return
     */
    public static Intent getImageFileIntent(String param) {
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(new File(param));
        intent.setDataAndType(uri, "image/*");
        return intent;
    }

    public static int getScreenWidth(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    public static int getScreenHeight(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    /**
     * ストリングはビットマップに転換する.
     *
     * @param string
     * @return　ビットマップ
     */
    public static Bitmap stringToBitmap(String string) {
        byte[] bytes = Base64.decode(string, Base64.DEFAULT);
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    public static Bitmap zoomImg(Bitmap bm, int newWidth) {
        int width = bm.getWidth();
        int height = bm.getHeight();

        float scaleWidth = ((float) newWidth) / width;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleWidth);
        Bitmap result = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
                true);
        return result;
    }

    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = null;
        ByteArrayInputStream isBm = null;
        Bitmap bitmap = null;
        try {
            baos = new ByteArrayOutputStream();
            image.compress(CompressFormat.JPEG, 100, baos);
            int options = 100;
            while (baos.toByteArray().length / 1024 > 100) {
                baos.reset();
                image.compress(CompressFormat.JPEG, options, baos);
                options -= 10;
            }
            isBm = new ByteArrayInputStream(baos.toByteArray());
            bitmap = BitmapFactory.decodeStream(isBm, null, null);
            baos.close();
            isBm.close();
        } catch (IOException e) {
            Log.e("AgentUtils", "compressImage", e);
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    Log.e("AgentUtils", "compressImage", e);
                }
            }
            if (isBm != null) {
                try {
                    isBm.close();
                } catch (IOException e) {
                    Log.e("AgentUtils", "compressImage", e);
                }
            }
        }
        return bitmap;
    }

    /**
     * 括弧の使用チェック
     *
     * @param str
     * @return
     */
    public static boolean checkBracket(String str) {
        if (str == null || str.length() == 0) {
            return true;
        } else {
            return Pattern.matches("[^〔〕()<>《》\\[\\]{}（）【】［］｛｝〈〉「」『』＜＞≪≫]+",
                    str);
        }
    }

    /**
     * 获取状态栏高度
     *
     * @param activity
     * @return > 0 success; <= 0 fail
     */
    public static int getStatusHeight(Activity activity) {
        int statusHeight = 0;
        Rect localRect = new Rect();
        activity.getWindow().getDecorView()
                .getWindowVisibleDisplayFrame(localRect);
        statusHeight = localRect.top;
        if (0 == statusHeight) {
            Class<?> localClass;
            try {
                localClass = Class.forName("com.android.internal.R$dimen");
                Object localObject = localClass.newInstance();
                int i5 = Integer.parseInt(localClass
                        .getField("status_bar_height").get(localObject)
                        .toString());
                statusHeight = activity.getResources()
                        .getDimensionPixelSize(i5);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        return statusHeight;
    }

    /**
     * 共通方法：拍照
     */
    public static void takePhotos(Context context, File currentFile,
                                  int requestCode) {
        Uri uri = null;
        // 启动照相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        try {
            // 在SD卡创建一个新的文件
            uri = Uri.fromFile(currentFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 设置输出路径到新建的文件
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        // 拍照回调
        ((Activity) context).startActivityForResult(intent, requestCode);
    }

    /**
     * 获取Bitmap实际大小
     *
     * @param originalBmp
     */
    public static void getBitmapSize(Bitmap originalBmp, String path) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        originalBmp.compress(CompressFormat.JPEG, 100, os);
        byte[] bytes = os.toByteArray();
        File mPhotoFile = AgentUtils.getFileFromBytes(bytes, path);
        FileInputStream fs;
        try {
            fs = new FileInputStream(mPhotoFile);
            int length;
            try {
                length = fs.available();
                Log.e("New File：", path + "   " + length / 1024 + "K");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 把单个英文字母或者字符串转换成数字ASCII码
     *
     * @param input
     * @return
     */
    public static int character2ASCII(String input) {
        char[] temp = input.toCharArray();
        StringBuilder builder = new StringBuilder();
        for (char each : temp) {
            builder.append((int) each);
        }
        String result = builder.toString();
        return Integer.parseInt(result);
    }

    /**
     * 文件转bitmap
     *
     * @param bitmapPath
     * @return
     */
    public static Bitmap decodeBitmap(String bitmapPath) {
        return BitmapFactory.decodeFile(bitmapPath);
    }

    /**
     * 格林尼治转本地
     *
     * @param gmt
     * @return
     */
    public static String convertGMTToLoacale(String gmt) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        return sdf.format(date);
        // String cc = gmt.substring(0, 19) + gmt.substring(33, 38);
        // SimpleDateFormat sdf = new
        // SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy",
        // Locale.ENGLISH);
        // try {
        // Date date = sdf.parse(cc);
        // SimpleDateFormat dateformat = new SimpleDateFormat(
        // "yyyy-MM-dd HH:mm:ss");
        // String result = dateformat.format(date);
        // return result;
        // } catch (ParseException e) {
        // }
        // return "";
    }

    /**
     * 获取外置SD卡路径
     *
     * @return
     */
    public static String getSDCardPath() {
        return Environment.getExternalStorageDirectory().toString();
    }

    /**
     * 获取内置空间路径
     *
     * @return
     */
    @SuppressLint("SdCardPath")
    public static String getDeviceCardPath() {
        return Environment.getExternalStorageDirectory().getParent()
                + "/sdcard1";
    }

    public static Bitmap reSizeBitmap(String filePath, int maxLength) {
        Bitmap bm = getSmallBitmap(filePath, maxLength);
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            bm.compress(CompressFormat.JPEG, 80, baos);
            baos.close();
        } catch (IOException e) {
            Log.e("ImageUtil", "reSizeBitmap", e);
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    Log.e("ImageUtil", "reSizeBitmap", e);
                }
            }
        }
        return bm;
    }

    public static Bitmap getSmallBitmap(String filePath, int maxLength) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        int width = options.outWidth;
        int height = options.outHeight;
        int reqWidth = 0;
        int reqHeight = 0;
        float scal = height / (float) width;
        float scal2 = width / (float) height;
        if (scal > scal2) {
            if (height > maxLength) {
                reqHeight = maxLength;
                reqWidth = (int) (reqHeight / scal);
            } else {
                reqHeight = height;
                reqWidth = width;
            }
        } else {
            if (width > maxLength) {
                reqWidth = maxLength;
                reqHeight = (int) (reqWidth / scal2);
            } else {
                reqWidth = width;
                reqHeight = height;
            }
        }
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * 获取等比例压缩后的图片
     *
     * @param filePath
     * @return
     */
    public static Bitmap getResizedBitmap(String filePath, int maxLength) {
        // 获取原始图片的宽高
        BitmapFactory.Options options = new BitmapFactory.Options();
        // 不读入内存
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        int height = options.outHeight;
        int width = options.outWidth;
        // 根据最长边的大小计算实际输出大小
        int reqWidth = 0;
        int reqHeight = 0;
        float scal = height / (float) width;
        float scal2 = width / (float) height;
        if (scal > scal2) {
            if (height > maxLength) {
                reqHeight = maxLength;
                reqWidth = (int) (reqHeight / scal);
            } else {
                reqHeight = height;
                reqWidth = width;
            }
        } else {
            if (width > maxLength) {
                reqWidth = maxLength;
                reqHeight = (int) (reqWidth / scal2);
            } else {
                reqWidth = width;
                reqHeight = height;
            }
        }
        // 压缩比例
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);
        // 在内存中创建Bitmap
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * 计算压缩比例
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    /**
     * 生成上传的文件
     *
     * @param bitmap
     * @param filePath
     * @param rate     压缩比例
     * @return
     */
    public static File getUploadBitmapFile(Bitmap bitmap, String filePath,
                                           int rate) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.JPEG, rate, os);
        byte[] bytes = os.toByteArray();
        File mPhotoFile = AgentUtils.getFileFromBytes(bytes, filePath);
        FileInputStream fs;
        try {
            fs = new FileInputStream(mPhotoFile);
            int length;
            try {
                length = fs.available();
                Log.e("New File：", filePath + "   " + length / 1024 + "K");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return mPhotoFile;
    }

    /**
     * MD5加密
     *
     * @param s
     * @return String
     */
    public static String MD5(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] strTemp = s.getBytes();
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str).toUpperCase();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 半角转全角
     *
     * @param input
     * @return
     */
    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375) {
                c[i] = (char) (c[i] - 65248);
            }
        }
        return new String(c);
    }

    /**
     * 用来判断服务是否运行.
     *
     * @param mContext
     * @param className 判断的服务名字
     * @return true 在运行 false 不在运行
     */
    public static boolean isServiceRunning(Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(1000);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className)) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    /**
     * 用来判断服务是否运行.
     *
     * @param mContext
     * @param packageName 判断的服务名字
     * @return true 在运行 false 不在运行
     */
    public static boolean isAppRunning(Context mContext, String packageName) {
        boolean isRunning = false;
        ActivityManager am = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> list = am.getRunningTasks(100);
        for (RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(packageName)
                    || info.baseActivity.getPackageName().equals(packageName)) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    /**
     * 设置子控件TextView不可用
     *
     * @param dp
     */
    public static void setDisabledEditTexts(ViewGroup dp) {
        for (int x = 0, n = dp.getChildCount(); x < n; x++) {
            View v = dp.getChildAt(x);
            if (v instanceof EditText) {
                v.setFocusable(false);
                v.setClickable(false);
                v.setFocusableInTouchMode(false);
                v.setLongClickable(false);
            } else if (v instanceof ViewGroup) {
                setDisabledEditTexts((ViewGroup) v);
            }
        }
    }

    /**
     * 产生随机字符串
     */
    public static String randomString(int length) {
        Random randGen = null;
        char[] numbersAndLetters = null;
        if (length < 1) {
            return null;
        }
        if (randGen == null) {
            randGen = new Random();
            numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz"
                    + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
        }
        char[] randBuffer = new char[length];
        for (int i = 0; i < randBuffer.length; i++) {
            randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
        }
        return new String(randBuffer);
    }

    /**
     * 获取通知栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        Class c = null;
        Object bj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            bj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(bj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public static boolean isGPSOpen(final Context context) {
        LocationManager locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    /**
     * 跳转到网络设置画面
     *
     * @param activity
     */
    public static void gotoGpsSystemSetting(Activity activity) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        activity.startActivityForResult(intent, 8888);
    }

    /**
     * 强制帮用户打开GPS
     *
     * @param context
     */
    public static void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (CanceledException e) {
            e.printStackTrace();
        }
    }

    public static List<String> getProviders(Context context) {
        LocationManager lm = ((LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE));
        return lm.getProviders(true);
    }

    /**
     * 返回byte的数据大小对应的文本
     *
     * @param size
     * @return
     */
    public static String formatFileSize(long size) {
        DecimalFormat formater = new DecimalFormat("####.00");
        if (size < 1024) {
            return size + "B";
        } else if (size < 1024 * 1024) {
            float kbsize = size / 1024f;
            return formater.format(kbsize) + "KB";
        } else if (size < 1024 * 1024 * 1024) {
            float mbsize = size / 1024f / 1024f;
            return formater.format(mbsize) + "MB";
        } else if (size < 1024 * 1024 * 1024 * 1024) {
            float gbsize = size / 1024f / 1024f / 1024f;
            return formater.format(gbsize) + "GB";
        } else {
            return "size: error";
        }
    }

    public static boolean isYunke(String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[A-Za-z]{1}[a-zA-Z0-9_\\-]*$");
        m = p.matcher(str);
        b = m.matches();
        return b;
    }

    /**
     * 手机号验证
     *
     * @param str
     * @return 验证通过返回true
     */
    public static boolean isMobile(String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[1][3,4,5,6,7,8][0-9]{9}$"); // 验证手机号
        m = p.matcher(str);
        b = m.matches();
        return b;
    }

    /**
     * 电话号码验证
     *
     * @param str
     * @return 验证通过返回true
     */
    public static boolean isPhone(String str) {
        Pattern p1 = null, p2 = null;
        Matcher m = null;
        boolean b = false;
        p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$"); // 验证带区号的
        p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$"); // 验证没有区号的
        if (str.length() > 9) {
            m = p1.matcher(str);
            b = m.matches();
        } else {
            m = p2.matcher(str);
            b = m.matches();
        }
        return b;
    }

    public static boolean isContainsNumberAndLetter(String str) {
        boolean isDigit = false;// 定义一个boolean值，用来表示是否包含数字
        boolean isLetter = false;// 定义一个boolean值，用来表示是否包含字母
        for (int i = 0; i < str.length(); i++) { // 循环遍历字符串
            if (Character.isDigit(str.charAt(i))) { // 用char包装类中的判断数字的方法判断每一个字符
                isDigit = true;
            }
            if (Character.isLetter(str.charAt(i))) { // 用char包装类中的判断字母的方法判断每一个字符
                isLetter = true;
            }
        }
        return isDigit && isLetter;
    }

    // 金额验证
    public static boolean isNumber(String str) {
        Pattern pattern = Pattern
                .compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
        Matcher match = pattern.matcher(str);
        return match.matches();
    }

    public static boolean isAllNumber(String str) {
        if (str == null || str.equalsIgnoreCase("")) {
            return false;
        }
        return str.matches("[0-9]+");
    }

    public static boolean isNotTab(String str) {
        char ch;
        for (int i = 0; i < str.length(); i++) {
            ch = str.charAt(i);

            if (Character.isWhitespace(ch))
                return false;

        }
        return true;

    }

    public static Integer checkVersionCode(Context context, Document document) {
        int localVersionCode = getPackageInfo(context).versionCode;
        int remoteVersionCode = Integer.parseInt(document.getDocumentElement()
                .getAttribute("android:versionCode"));
        return localVersionCode - remoteVersionCode;
    }

    public static String getAppPath() {
        StringBuilder sb = new StringBuilder();
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            sb.append(Environment.getExternalStorageDirectory().getPath());
        } else {
            sb.append(Environment.getDataDirectory().getPath());
        }
        sb.append(File.separator);
        sb.append(AgentConstants.AGENT_NAME);
        sb.append(File.separator);
        return sb.toString();
    }

    public static String getCachePath() {
        StringBuilder sb = new StringBuilder();
        sb.append(getAppPath());
        sb.append(AgentConstants.CACHE_PATH);
        sb.append(File.separator);
        existDir(sb.toString());
        return sb.toString();
    }

    public static String getImageCachePath() {
        StringBuilder sb = new StringBuilder();
        sb.append(getCachePath());
        sb.append(AgentConstants.IMAGE_PATH);
        existDir(sb.toString());
        return sb.toString();
    }

    public static String getAudioCachePath() {
        StringBuilder sb = new StringBuilder();
        sb.append(getCachePath());
        sb.append(AgentConstants.AUDIO_PATH);
        existDir(sb.toString());
        return sb.toString();
    }

    public static String getFileCachePath() {
        StringBuilder sb = new StringBuilder();
        sb.append(getCachePath());
        sb.append(AgentConstants.FILE_PATH);
        existDir(sb.toString());
        return sb.toString();
    }

    public static void existDir(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public static String getDBPath() {
        StringBuffer sb = new StringBuffer();
        sb.append(getCachePath());
        sb.append("xkzp_customer.db");
        return sb.toString();
    }

    private static SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm");
    private static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat sdf3 = new SimpleDateFormat("hh:mm");

    public static String formatTime(long timestamp) {
        Calendar now = Calendar.getInstance();
        Calendar time = Calendar.getInstance();
        time.setTimeInMillis(timestamp);
        if (now.getTimeInMillis() - time.getTimeInMillis() <= 0) {
            return sdf2.format(time.getTime());
        } else if (now.getTimeInMillis() - time.getTimeInMillis() < 60000) {
            return "刚刚";
//		}
//		else if(now.get(Calendar.DATE)-1 == time.get(Calendar.DATE))
//		{
//			if (time.get(Calendar.HOUR_OF_DAY) < 12) {
//				// 昨天
//				return "昨天 上午" + sdf3.format(time.getTime());
//			} else {
//				return "昨天 下午" + sdf3.format(time.getTime());
//			}
        } else if (now.get(Calendar.HOUR) - time.get(Calendar.HOUR) <= now
                .get(Calendar.HOUR_OF_DAY)) {
            if (time.get(Calendar.HOUR_OF_DAY) < 12) {
                // 今天
                return "今天 上午" + sdf3.format(time.getTime());
            } else {
                return "今天 下午" + sdf3.format(time.getTime());
            }
        }
//		else if (now.get(Calendar.DATE) - time.get(Calendar.HOUR) <= 24 + now
//				.get(Calendar.HOUR_OF_DAY)) {
//			// 昨天
//			return "昨天";
//		}
        else {
            return sdf2.format(new Date(timestamp));
        }
    }

    public static File createImageUri() throws Exception {
        String fileName = "take_photo_temp.jpg";
        File fileFolder = new File(getImageCachePath());
        if (!fileFolder.exists()) {
            fileFolder.mkdirs();
        }
        File jpgFile = new File(fileFolder, fileName);
        if (!jpgFile.exists()) {
            jpgFile.createNewFile();
        }
        return jpgFile;
    }

    /**
     * Get real path
     */
    public static String getRealImagePath(Activity activity, Uri uri) {
        if (uri.toString().startsWith("content")) {
            String[] proj = {MediaColumns.DATA};
            Cursor cursor = activity.managedQuery(uri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else if (uri.toString().startsWith("file")) {
            String tempUri = Uri.decode(uri.toString());
            return tempUri.substring(7, tempUri.length());
        } else {
            return "";
        }
    }

    /**
     * 将bigmap保存为文件
     *
     * @param bp
     * @throws IOException
     */
    public static String saveBitmap(Bitmap bp) {

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss",
                Locale.US); // 格式化时间
        String fileName = format.format(new Date()) + ".jpg";
        File fileFolder = null;

        FileOutputStream fos = null;
        try {
            fileFolder = new File(getImageCachePath());
            if (!fileFolder.exists()) { // 如果目录不存在，则创建一个名为"CTC"的目录
                fileFolder.mkdirs();
            }
            File f = new File(fileFolder, fileName);
            if (!f.exists()) {
                f.createNewFile();
            }
            fos = new FileOutputStream(f);
            // 每当执行到这时就抛出异常FileNotFoundException
            bp.compress(CompressFormat.JPEG, 100, fos);

        } catch (FileNotFoundException e) {
            fileName = AgentConstants.BLANK;
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            fos.flush();
            fos.close();
        } catch (IOException e) {
            fileName = AgentConstants.BLANK;
            e.printStackTrace();
        }

        return fileFolder + "/" + fileName;
    }

    public static void saveBitmap(Bitmap bp, File path) throws IOException {

        FileOutputStream fos = null;
        try {
            if (!path.exists()) {
                path.createNewFile();
            }
            fos = new FileOutputStream(path);
            // 每当执行到这时就抛出异常FileNotFoundException
            bp.compress(CompressFormat.JPEG, 100, fos);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        fos.flush();
        fos.close();
    }

    public static boolean isImageResource(String filename) {

        String suffix = filename.substring(filename.lastIndexOf(".") + 1,
                filename.length());
        if (StringUtils.isBlank(suffix)) {
            return false;
        }
        switch (suffix.toLowerCase()) {
            case "jpg":
            case "jpeg":
            case "png":
                return true;
            default:
                return false;
        }

    }

    public static String getFileType(String filename) {
        String resource = "文件类型：未知";
        // 获取后缀名
        String suffix = filename.substring(filename.lastIndexOf(".") + 1,
                filename.length());
        if (StringUtils.isBlank(suffix)) {
            return resource;
        }
        resource = "文件类型：" + suffix.toLowerCase();

        return resource;
    }

    public static String intWeekToStrWeek(int weekInt) {
        String weekStr = "一";
        switch (weekInt) {
            case 2:
                weekStr = "一";
                break;
            case 3:
                weekStr = "二";
                break;
            case 4:
                weekStr = "三";
                break;
            case 5:
                weekStr = "四";
                break;
            case 6:
                weekStr = "五";
                break;
            case 7:
                weekStr = "六";
                break;
            case 1:
                weekStr = "日";
                break;
            default:
                break;
        }
        return weekStr;
    }

    public static String sqliteEscape(String keyWord) {
        keyWord = keyWord.replace("/", "//");
        keyWord = keyWord.replace("'", "''");
        keyWord = keyWord.replace("[", "/[");
        keyWord = keyWord.replace("]", "/]");
        keyWord = keyWord.replace("%", "/%");
        keyWord = keyWord.replace("&", "/&");
        keyWord = keyWord.replace("_", "/_");
        keyWord = keyWord.replace("(", "/(");
        keyWord = keyWord.replace(")", "/)");
        return keyWord;
    }

    public static boolean isTopActivity(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        if (am == null) {
            return false;
        }
        List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        if (taskInfo != null && taskInfo.size() > 0) {
            if (context.getPackageName().equals(
                    taskInfo.get(0).topActivity.getPackageName()) || "com.android.gallery3d".equals(
                    taskInfo.get(0).topActivity.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    public static String getImageFirst(String imageUrlJson) {
        if (StringUtils.isBlank(imageUrlJson)) {
            return "";
        }
//        return imageUrlJson.split(",")[0];
        String[] array = imageUrlJson.split(",");
        if (array.length == 0)
            return "";
        else
            return array[0];
    }

    /**
     * 校验18位身份证号
     *
     * @param identityCode 返回true则表示校验通过
     */
    public boolean checkIdentityCode(String identityCode) {
        // 校验身份证位数为18位
        if (!identityCode.matches("\\d{17}(\\d|x|X)$")) {
            return false;
        }
        Date d = new Date();
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        int year = Integer.parseInt(df.format(d));
        if (Integer.parseInt(identityCode.substring(6, 10)) < 1900
                || Integer.parseInt(identityCode.substring(6, 10)) > year) {// 7-10位是出生年份，范围应该在1900-当前年份之间
            return false;
        }
        if (Integer.parseInt(identityCode.substring(10, 12)) < 1
                || Integer.parseInt(identityCode.substring(10, 12)) > 12) {// 11-12位代表出生月份，范围应该在01-12之间
            return false;
        }
        if (Integer.parseInt(identityCode.substring(12, 14)) < 1
                || Integer.parseInt(identityCode.substring(12, 14)) > 31) {// 13-14位是出生日期，范围应该在01-31之间
            return false;
        }
        // 校验第18位
        // S = Sum(Ai * Wi), i = 0, ... , 16 ，先对前17位数字的权求和
        // Ai:表示第i位置上的身份证号码数字值
        // Wi:表示第i位置上的加权因子
        // Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
        String[] tempA = identityCode.split("|");
        int[] a = new int[18];
        for (int i = 0; i < tempA.length - 2; i++) {
            a[i] = Integer.parseInt(tempA[i + 1]);
        }
        int[] w = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; // 加权因子
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum = sum + a[i] * w[i];
        }
        // Y = mod(S, 11)
        // 通过模得到对应的校验码
        // Y: 0 1 2 3 4 5 6 7 8 9 10
        // 校验码: 1 0 X 9 8 7 6 5 4 3 2
        String[] v = {"1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2"}; // 校验码
        int y = sum % 11;
        if (!v[y].equalsIgnoreCase(identityCode.substring(17))) {// 第18位校验码错误
            return false;
        }
        return true;
    }

    //格式化价格显示两位小数
    public static String getFormatPrice(String price) {
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        if (StringUtils.isBlank(price)) {
            return "";
        }
        return decimalFormat.format(Float.parseFloat(price));
    }

    public static String getFormatPrice(Float price) {
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(price);
    }

    public static String getFormatAddress(String province, String city, String district, String street, String title, String address) {
        StringBuffer sb = new StringBuffer();
        if (!StringUtils.isBlank(province)) {
            sb.append(province);
            sb.append(" ");
        }
        if (!StringUtils.isBlank(city) && !city.equals(province)) {
            sb.append(city);
            sb.append(" ");
        }
        if (!StringUtils.isBlank(district) && !district.equals(city)) {
            sb.append(district);
            sb.append(" ");
        }
        if (!StringUtils.isBlank(street) && !street.equals(district)) {
            sb.append(street);
            sb.append(" ");
        }
        if (!StringUtils.isBlank(title) && !title.equals(street)) {
            sb.append(title);
            sb.append(" ");
        }
        if (!StringUtils.isBlank(address) && !address.equals(title)) {
            sb.append(address);
        }
        return sb.toString();
    }
}
